package com.demo.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.demo.config.db.JDBCConnection;
import com.demo.dao.UsersDao;
import com.demo.model.Users;

public class UsersDaoImpl implements UsersDao{

	@Override
	public boolean saveOrUpdate(String sql) throws SQLException {
		// 对数据库的添加修改删除方法
		
		//1.创建数据库创建出来的一次链接（每个链接都有一定的有效时常，不是创建了就能一直用）
		//2.statement 针对数据库做增加、删除、修改、查询。statement是由connection创造的，没有connection就没有statement
		Connection connection=JDBCConnection.getConnection();
		Statement stat=connection.createStatement();
		int b=stat.executeUpdate(sql);//失败是-1，成功是0或者是1不一定
		JDBCConnection.closeStatement(stat);
		JDBCConnection.closeConnection(connection);
		return b!=-1;
	}

	@Override
	public List<Users> find(String sql)throws SQLException {
		// 查询全部
		Connection connection=JDBCConnection.getConnection();
		Statement stat=connection.createStatement();
		ResultSet rs=stat.executeQuery(sql);
		List<Users> list=new ArrayList<Users>();
		while (rs.next()){
			Users user=new Users();
			user.setId(rs.getString("id"));
			user.setLoginname(rs.getString("loginname"));
			user.setPassword(rs.getString("password"));
			user.setUsername(rs.getString("username"));
			list.add(user);
		}
		JDBCConnection.closeResultSet(rs);
		JDBCConnection.closeStatement(stat);
		JDBCConnection.closeConnection(connection);
		return list;
	}

	@Override
	public Users findById(String sql) throws SQLException {
		// 根据id查询
		Connection connection=JDBCConnection.getConnection();
		Statement stat=connection.createStatement();
		ResultSet rs=stat.executeQuery(sql);
		Users user=new Users();

		while (rs.next()){
			user.setId(rs.getString("id"));
			user.setLoginname(rs.getString("loginname"));
			user.setPassword(rs.getString("password"));
			user.setUsername(rs.getString("username"));
		}
		JDBCConnection.closeResultSet(rs);
		JDBCConnection.closeStatement(stat);
		JDBCConnection.closeConnection(connection);
		return user;
	}

	
}
